var expandRowId;
$(function() {
	//加载表格树数据
	loadTreeGridData();
	//表格上方新增按钮点击事件
	$('#btnAdd').on('click', function(){
		$("#layer_opt_status").val("");
		showDialogUrl('新增一级分类', 800,  550, 
			rootPath + '/productCategory/toAddProductCategory',
			function(){
				var layer_opt_status = $("#layer_opt_status").val();
				if (layer_opt_status == "1") {
					loadTreeGridData();
				}
			}
		);
	})
	//查询
	$('#btnQuery').on('click', function(){
		loadTreeGridData();
	})
	//清空
	$('#btnClear').on('click', function(){
		$('#categoryName').val("");
	})
})
/**
 * 加载表格树数据
 */
var loadTreeGridData = function(){
	var url = rootPath + "/productCategory/listProductCategoryPage"; // 请求json数据的服务器地址
	var categoryName = $('#categoryName').val(); 
	$.ajax({
		type: 'POST',
		url: url,
		async: true,
		data: {categoryName: categoryName},
		dataType: 'json',
		success: function(data) {
			if (data) {
				initTreeGrid(data.rows);
			}
		}
	})
}
/**
 * 初始化表格树
 * @param rows 行JSON数据集合
 */
var initTreeGrid = function(rows) {
	// prepare the data
	var source = { 
		dataType : "json", 
		dataFields : [ 
		    { name : 'id', type : 'number' }, 
		    { name : 'parentCategoryId', type : 'number' }, 
		    { name : 'categoryName', type : 'string' }, 
		    { name : 'productAmount', type : 'number' }, 
		    { name : 'status', type : 'number' }
		],
		hierarchy : {
			keyDataField : { name : 'id' },
			parentDataField : { name : 'parentCategoryId' }
		},
		id : 'id',
		localData : rows
	};

	var dataAdapter = new $.jqx.dataAdapter(source);
	// create Tree Grid
	$("#treeGrid").jqxTreeGrid(
	{
		width: '100%',
		columnsHeight: 40,
		autoRowHeight: true,
		columnsResize: true,
		altRows: true,
		source: dataAdapter,
		theme: 'office',
		sortable: false,
		columns: [
		   { text: '分类名称', dataField: 'categoryName', width: 400, align: "center" },
	       { text: '商品数量', dataField: 'productAmount', width: 200, align: "center", cellsalign: "center" },
	       { text: '状态', dataField: 'status', width: 150, align: "center", cellsalign: "center",
	    	   cellsrenderer: function (row, column, value, rowData) {
	    		   if (value == '0') {
	    			   return "<span id='statuslabel"+rowData.id+"' class='label label-danger'>停用</span>";
	    		   } else {
	    			   return "<span id='statuslabel"+rowData.id+"' class='label label-success'>启用</span>";
	    		   }
	           }
	       },
	       { text: '排序', dataField: '#', align: "center", cellsalign: "center",
	    	   cellsrenderer: function (row, column, value, rowData) {
	    		    var levelRowIndex, cLevelRowIndex; 
	    		    var cRecord = null;
	    		    var rows = $("#treeGrid").jqxTreeGrid('getRows'); 
	    		    for (var i = 0; i < rows.length; i++) {
	    		          var myData = rows[i]; 
	    		          if (rowData.id == myData.id) {
	    		        	  levelRowIndex = i;
	    		        	  break;
	    		          }
	    		   	} 
	    		    for (var i = 0; i < rows.length; i++) {
	    		          var myData = rows[i]; 
	    		          if (myData && myData.records) {
	    		        	  for (var j = 0; j < myData.records.length; j++) {
	    		        		  if (rowData.id == myData.records[j].id) {
	    		        			  cLevelRowIndex = j;
	    		        			  cRecord = myData.records;
	    	    		        	  break;
	    	    		          }
		    		          }
	    		          }
	    		   	} 
	    			var strHtml = "";
	    			if (levelRowIndex != 0 && cLevelRowIndex != 0) {
	    				strHtml += "<a class='btn btn-primary btn-xs' onclick='sort(1, "+rowData.id+", "+rowData.parentCategoryId+")'><i class='fa fa-arrow-up'></i>上移</a>";
	    			}
	    			if (rows[rows.length - 1].id != rowData.id ) 
	    				if (cRecord == null) {
	    					strHtml += "<a class='btn btn-primary btn-xs' onclick='sort(-1, "+rowData.id+", "+rowData.parentCategoryId+")'><i class='fa fa-arrow-down'></i>下移</a>";
	    				} else { 
	    					if (cRecord[cRecord.length -1].id != rowData.id) {
	    						strHtml += "<a class='btn btn-primary btn-xs' onclick='sort(-1, "+rowData.id+", "+rowData.parentCategoryId+")'><i class='fa fa-arrow-down'></i>下移</a>";
	    					}
	    				}
	    					
	    			if (levelRowIndex != 0 && cLevelRowIndex != 0) {
	    				strHtml += "<a class='btn btn-primary btn-xs' onclick='sort(0, "+rowData.id+", "+rowData.parentCategoryId+")'>置顶</a>";
	    			}
	    			return strHtml;
	    	   }
	       },
	       { text: '操作', dataField: 'id', align: "center", cellsalign: "center",
	    	   cellsrenderer: function (row, column, value, rowData) {
	    		   var strHtml = '';
	    		   strHtml += "";
	    		   if (rowData.status == '0') {
	    			   strHtml += "<a id='statusbtn"+rowData.id+"' class='btn btn-primary btn-xs btn-category-status' bind-id='"+rowData.id+"' bind-data='"+rowData.status+"'>启用</a>";
	    		   } else {
	    			   strHtml += "<a id='statusbtn"+rowData.id+"' class='btn btn-danger btn-xs btn-category-status' bind-id='"+rowData.id+"' bind-data='"+rowData.status+"'>停用</a>";
	    		   }
	    		   strHtml += "<a class='btn btn-success btn-xs btn-add-category'  bind-data='"+rowData.id+"'>新增</a>";
	    		   strHtml += "<a class='btn btn-warning btn-xs btn-edit-category' bind-data='"+rowData.id+"'>编辑</a>";
	    		   strHtml += "<a class='btn btn-danger btn-xs btn-remove-category'bind-data='"+rowData.id+"'>删除</a>";
	    		   strHtml += "<a class='btn btn-info btn-xs btn-relation-category'bind-data='"+rowData.id+"'>关联设置</a>";
	               return strHtml;  
	           }
	       }
	    ],
	    rendered: function() {
	    	$("#treeGrid").jqxTreeGrid('focus');
	    	if (expandRowId) { 
	    		$("#treeGrid").jqxTreeGrid('expandRow', expandRowId);
	    	}
	    	expandRowId = null;
	    	//新增
	    	$('.btn-add-category').on('click', function(){
	    		var parentCategoryId = $(this).attr('bind-data');
	    		if (!parentCategoryId) return;
	    		$("#layer_opt_status").val(""); //初始化弹出框操作状态
	    		var index = showDialogUrl('新增分类', 800, 550, rootPath + '/productCategory/toAddProductCategory?parentCategoryId='+parentCategoryId,
	    			function(){
						var layer_opt_status = $("#layer_opt_status").val(); //获取弹出框操作状态(确定1 取消 0)
						if (layer_opt_status == "1") { //如果是确定
							loadTreeGridData();
						}
						$("#treeGrid").jqxTreeGrid('focus');
					}
	    		);
	    		layer.full(index);
	    	});
	    	//编辑
	    	$('.btn-edit-category').on('click', function(){
	    		var id = $(this).attr('bind-data');
	    		if (!id) return;
	    		$("#layer_opt_status").val(""); //初始化弹出框操作状态
	    		var index = showDialogUrl('编辑分类', 800, 550, rootPath + '/productCategory/toUpdateProductCategory?id='+id,
	    			function(){
						var layer_opt_status = $("#layer_opt_status").val(); //获取弹出框操作状态(确定1 取消 0)
						if (layer_opt_status == "1") { //如果是确定
							loadTreeGridData();
						}
						$("#treeGrid").jqxTreeGrid('focus');
					}
	    		);
	    		layer.full(index);
	    	});
	    	//删除
	    	$('.btn-remove-category').on('click', function(){
	    		var id = $(this).attr('bind-data');
	    		layer.confirm("确定要删除？", {
	    				btn: ['确定','取消'], //按钮
	    				skin: 'layui-layer-lan' //样式类名
					}, function(index){
						$.ajax({
    						type: 'POST',
    						url: rootPath + "/productCategory/removeProductCategoryById",
    						async: false,
    						data: {id: id},
    						dataType: 'json',
    						success: function(data) {
    							if (data.code == '1') {
    								$("#treeGrid").jqxTreeGrid('deleteRow', id);
    								//loadTreeGridData();
    							} else {
    								layer.msg(data.msg, {icon: 2});
    							}
    						}
    					});
						layer.close(index);
						$("#treeGrid").jqxTreeGrid('focus');
					} , function(){
						$("#treeGrid").jqxTreeGrid('focus');
					}
	    		);
	    	});
	    	//关联设置
	    	$('.btn-relation-category').on('click', function(){
	    		var id = $(this).attr('bind-data');
	    		$("#layer_opt_status").val(""); //初始化弹出框操作状态
	    		var url = rootPath + '/productCategory/toProductCategoryRelationSettingsPage?productCategoryId='+id;
	    		var index = showDialogUrl('关联设置', 1200, 750, url, function(index){
	    			var optStatus = $('#layer_opt_status').val();
	    			if (optStatus == '1') {
	    				 
	    			}
	    			layer.close(index);
	    			$("#treeGrid").jqxTreeGrid('focus');
	    		})
	    		layer.full(index);
	    	})
	    	//状态停用/启用
	    	$('.btn-category-status').on('click', function(){ 
	    		var id = $(this).attr('bind-id');  
	    		var status = $(this).attr('bind-data');  
	    		var confirmInfo = "";
	    		if (status == '0') {
	    			confirmInfo = "您确定要启用？";
	    		} else {
	    			confirmInfo = "您确定要停用？";
	    		}
	    		layer.confirm(confirmInfo, {
	    				btn: ['确定','取消'], //按钮
	    				skin: 'layui-layer-lan' //样式类名
    				}, function(index){
    					var newStatus = status == '0' ? '1' : '0';
    					$.ajax({
    						type: 'POST',
    						url: rootPath + "/productCategory/saveOrUpdateProductCategory",
    						async: false,
    						data: {id: id, status: newStatus},
    						dataType: 'json',
    						success: function(data) {
    							if (data.code == '1') {
    								var row = $("#treeGrid").jqxTreeGrid('getRow', id);
    								row.status = newStatus;
    								$("#treeGrid").jqxTreeGrid('updateRow', id, row);
    								if (newStatus == '0') {
    									$('#statuslabel').removeClass().addClass('label label-danger');
    									$('#statusbtn').removeClass().addClass('btn btn-primary btn-xs btn-category-status');
    								} else {
    									$('#statuslabel').removeClass().addClass('label label-success');
    									$('#statusbtn').removeClass().addClass('btn btn-danger btn-xs btn-category-status');
    								}
    								//loadTreeGridData();
    							}
    						}
    					});
    					layer.close(index);
    					$("#treeGrid").jqxTreeGrid('focus');
    				} , function(){ 
    					$("#treeGrid").jqxTreeGrid('focus');
    				}
	    		);
	    	});
	    	
	    }
	});

}

/**
 * 排序
 * 
 * @param direction
 *            排序移动方向 1 上移 0 置顶 -1 下移
 * @param id
 *            主键ID
 */
function sort(direction, id, parentId) {
	var url = rootPath + '/sort';
	var tableName = "eb_product_category";
	$.ajax({
		type: 'POST',
		url: url,
		data: {direction: direction, tableName: tableName, id: id, parentColumnName: 'PARENT_CATEGORY_ID', parentId: parentId},
		success: function(data){
			if (data.code == '1') {
				expandRowId = parentId;
				loadTreeGridData();
			}
		}
	})
}

 